<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Forms\RechargeRecordForm;
use App\Modules\Recharge\RechargeRecord;
use App\Modules\Recharge\UserBalance;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;

class RechargeRecordController extends Controller
{
    public function rechargeRecordIndex(Request $request)
    {

        $this->authorize('recharge_record');
        $orderId = $request->input('order_id');
        $name = $request->input('name');
        $start = $request->input('start');
        $end = $request->input('end');

        $rechargeRecords = RechargeRecord::query()
            ->leftJoin('shops AS s', 'recharge_records.shop_id', '=', 's.id')
            ->leftJoin('users AS u', 'recharge_records.user_id', '=', 'u.id')
            ->orderBy('recharge_records.created_at', 'desc');
        if ($orderId != '') $rechargeRecords->where('recharge_records.order_id', '=', $orderId);

        if ($name != '') {
            $rechargeRecords->where(function ($q) use ($name) {
                return $q->where('u.nickname', 'like', "%" . $name . "%")
                    ->orWhere('u.mobile', 'like', "%" . $name . "%")
                    ->orWhere('u.name', 'like', "%" . $name . "%");
            });
        }

        // if ($name != '') $rechargeRecords->where('u.nickname', 'like', '%' . $name . "%");
        if ($start != '') $rechargeRecords->where('recharge_records.created_at', '>', $start . ' 00:00:00');
        if ($end != '') $rechargeRecords->where('recharge_records.created_at', '<', $end . ' 23:59:59');

        $count = $rechargeRecords->count();
        $cz_money = $rechargeRecords->sum('recharge_records.cz_money');
        $zs_money = $rechargeRecords->sum('recharge_records.zs_money');

        $userIds = $rechargeRecords->pluck('user_id')->all();
        $userBalances = UserBalance::query()->whereIn('user_id', $userIds)->get();
        $aUserBalance = [];
        if ($userBalances) {
            foreach ($userBalances as $k => $v) {
                $aUserBalance[$v->user_id.'_'.$v->shop_id] = $v;
            }
        }

        $data = $rechargeRecords
            ->select('recharge_records.*', 'u.nickname', 'u.avatar', 's.id as shop_id', 's.name as shop_name')
            ->paginate(20)
            ->appends($request->all());
        
        return view('recharge_record.index', compact('data', 'count', 'orderId', 'name', 'start', 'end', 'cz_money', 'zs_money', 'aUserBalance'));
    }

    public function recharge(Request $request)
    {
        $this->authorize('recharge_record_recharge');
        $user_id = $request->input('user_id');
        $form = $this->form(RechargeRecordForm::class, [
            'url' => route('admin.rechargeRecord.store'),
            'method' => 'POST',
            'model' => ['user_id' => $user_id],
        ]);
        $flag = 'recharge';
        return view('recharge_record.form', compact('form', 'flag'));
    }


    public function store()
    {
        $form = $this->form(RechargeRecordForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $level = 0;
        DB::beginTransaction();
        try {
            $data = $form->getFieldValues();
            //设置充值状态、充值方式、计算当前余额、生成订单号
            $data['status'] = RechargeRecord::PAID;
            $data['recharge_mode'] = RechargeRecord::SYSTEM_RECHARGE;
            $user = Auth::user();
            $data['operator'] = $user->name;
            $data['total'] = $data['cz_money'] + $data['zs_money'];
            $data['order_no'] = Uuid::uuid4()->getHex();

            // 查看用户身份, 跳转不同地址
            $oUser = User::query()->where('id', $data['user_id'])->first('level');
            $level = $oUser->level;

            RechargeRecord::query()->create($data);
            $userBalance = UserBalance::query()->where(["user_id" => $data['user_id'], "shop_id" => $data['shop_id']])->first();
            if ($userBalance) {
                UserBalance::query()
                    ->where(["user_id" => $data['user_id'], "shop_id" => $data['shop_id']])
                    ->increment("balance", $data['total']);
            } else {
                $userBalanceData = [
                    "user_id" => $data['user_id'],
                    "shop_id" => $data['shop_id'],
                    "balance" => $data['total'],
                ];
                UserBalance::query()->create($userBalanceData);
            }
            $shop = Shop::query()->find($data['shop_id']);
            $userBalance = UserBalance::query()->where(["user_id" => $data['user_id'], "shop_id" => $data['shop_id']])->first();
            $qd_user = User::query()->find($data['user_id']);
            /**
             * 临洮：充值成功
             * {{first.DATA}}
             * 充值金额：{{keyword1.DATA}}
             * 充值时间：{{keyword2.DATA}}
             * 充值门店：{{keyword3.DATA}}
             * 当前余额：{{keyword4.DATA}}
             * {{remark.DATA}}
             */
            $sendData = [
                $qd_user->openid,
                date("Y年m月d日 H时i分s秒"),
                $shop->name,
                $data['cz_money'] . "元",
                $data['zs_money'] . "元",
                $userBalance->balance . "元"
            ];
            sendMessage(35, $sendData);
            DB::commit();
        } catch (\Exception $e) {
            throw $e;
            DB::rollBack();
        }

        // 确定用户跳转的链接
        if ($level == 1) {
            $url = 'admin.user.index';
            $params = ['level' => 1];
        } else if ($level == 2){
            $url = 'admin.user.index';
            $params = ['level' => 2];
        } else if ($level == 3){
            $url = 'admin.user.staff';
            $params = [];
        } else {
            $url = 'admin.user.index';
            $params = [];
        }
        
        return redirect()->route($url, $params);
    }
}
